package com.talkweb.historylib.component;

import com.talkweb.historylib.ResourceTable;
import com.talkweb.historylib.dialog.BottomInputDialog;
import com.talkweb.historylib.dialog.SearchByDateDialog;
import com.talkweb.historylib.dialog.SelectSearchTypeDialog;
import com.talkweb.historylib.fraction.ImageHistoryListFraction;
import com.talkweb.historylib.fraction.VideoHistoryListFraction;
import com.talkweb.securitycamera.common.base.BaseFraction;
import com.talkweb.securitycamera.common.base.BaseFractionAbilitySlice;
import com.talkweb.securitycamera.common.base.utils.ResourceHelper;
import com.talkweb.securitycamera.common.constans.FileType;
import com.talkweb.securitycamera.common.interfaces.dataprocess.IFileProcessor;
import com.talkweb.securitycamera.common.interfaces.entity.IBaseFileEntity;
import com.talkweb.securitycamera.common.interfaces.history.ICameraProcessor;
import com.talkweb.securitycamera.common.interfaces.history.IHistory;
import com.talkweb.securitycamera.utils.DensityUtils;
import com.talkweb.securitycamera.utils.TimeUtils;
import ohos.aafwk.ability.fraction.FractionManager;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.utils.Rect;
import ohos.app.dispatcher.task.Revocable;
import ohos.app.dispatcher.task.TaskPriority;

import java.util.List;

/**
 * @author SUQI
 * @date 2021/1/27
 * @description 历史记录界面
 **/
public class HistoryListComponent extends DirectionalLayout implements IHistory, Component.BindStateChangedListener {
    private BaseFractionAbilitySlice abilitySlice;
    private Text tvVideo;
    private Text tvImage;
    private Image ivMore;
    private VideoHistoryListFraction videoHistoryListFraction;
    private ImageHistoryListFraction imageHistoryListFraction;
    private ICameraProcessor cameraProcessor;
    private FractionManager fractionManager;
    private String dispatcherName = "queryDispatcher";
    private Revocable revocable;
    //记录当前展示那个fraction
    private FileType currentTypePage = FileType.FILE_TYPE_VIDEO;

    public HistoryListComponent(BaseFractionAbilitySlice abilitySlice, ICameraProcessor cameraProcessor) {
        super(abilitySlice);
        this.abilitySlice = abilitySlice;
        this.cameraProcessor = cameraProcessor;
        fractionManager = abilitySlice.getFractionManager();
        init();
        initEvent();
    }


    /**
     * 视图初始化
     */
    private void init() {
        Component mRootComponent = LayoutScatter.getInstance(abilitySlice).parse(ResourceTable.Layout_layout_history_list_component, null, false);
        tvVideo = (Text) mRootComponent.findComponentById(ResourceTable.Id_tv_video);
        tvImage = (Text) mRootComponent.findComponentById(ResourceTable.Id_tv_image);
        ivMore = (Image) mRootComponent.findComponentById(ResourceTable.Id_iv_more);
        addComponent(mRootComponent);
    }

    /**
     * 内嵌fraction初始化
     */
    public void initFraction() {
        videoHistoryListFraction = new VideoHistoryListFraction();
        abilitySlice.addFraction(ResourceTable.Id_fraction_container, videoHistoryListFraction, VideoHistoryListFraction.class.getName());
    }

    /**
     * 事件触发
     */
    private void initEvent() {
        setBindStateChangedListener(this);
        tvVideo.setClickedListener(component -> {
            //去除重复点击
            if (currentTypePage != FileType.FILE_TYPE_VIDEO) {
                currentTypePage = FileType.FILE_TYPE_VIDEO;
                changeState(tvVideo, true);
                changeState(tvImage, false);
                switchFraction(getVideoHistoryListFraction());
            }
        });
        tvImage.setClickedListener(component -> {
            if (currentTypePage != FileType.FILE_TYPE_IMAGE) {
                currentTypePage = FileType.FILE_TYPE_IMAGE;
                changeState(tvVideo, false);
                changeState(tvImage, true);
                switchFraction(getImageHistoryListFraction());
            }
        });
        ivMore.setClickedListener(component -> {
            SelectSearchTypeDialog dialog = new SelectSearchTypeDialog(abilitySlice, ivMore, new SelectSearchTypeDialog.OnDialogItemClickedListener() {
                @Override
                public void onSearchName() {
                    showInputDialog();
                }

                @Override
                public void onSearchTime() {
                    showSearchByDateDialog();
                }
            });
            int[] location = ivMore.getLocationOnScreen();
            dialog.showOnCertainPosition(LayoutAlignment.TOP | LayoutAlignment.RIGHT, ivMore.getMarginRight(), location[1] + ivMore.getHeight() + DensityUtils.vp2px(5));
        });
    }

    /**
     * 更新点击后界面
     *
     * @param text
     * @param isClicked
     */
    private void changeState(Text text, boolean isClicked) {
        text.setTextColor(isClicked ? Color.WHITE : Color.BLACK);
        ShapeElement element = new ShapeElement(abilitySlice, isClicked ? ResourceTable.Graphic_background_shape_text_video_selected :
                ResourceTable.Graphic_background_shape_text_video_unselected);
        text.setBackground(element);
    }

    /**
     * 按日期筛选
     */
    private void showSearchByDateDialog() {
        SearchByDateDialog searchByDateDialog = new SearchByDateDialog(abilitySlice, new SearchByDateDialog.OnDateSelectionCompleteListener() {
            @Override
            public void onDown(String startDate, String endDate) {
                revocable = abilitySlice.createSerialTaskDispatcher(dispatcherName, TaskPriority.DEFAULT).asyncDispatch(() -> {
                    IFileProcessor processor = cameraProcessor.getCameraProcessor(currentTypePage);
                    List<IBaseFileEntity> list = processor.getFileListByTime(TimeUtils.string2Millis(startDate, TimeUtils.FORMAT_PATTERN),
                            TimeUtils.string2Millis(endDate, TimeUtils.FORMAT_PATTERN), currentTypePage);
                    updateFraction(list, currentTypePage);
                });
            }
        });
        searchByDateDialog.show();
    }

    /**
     * 弹出文件名输入弹窗
     */
    private void showInputDialog() {
        BottomInputDialog inputDialog = new BottomInputDialog(abilitySlice);
        inputDialog.setTvTitle(ResourceHelper.getString(abilitySlice, ResourceTable.String_input_file_name));
        inputDialog.setListener(new BottomInputDialog.OnClickListener() {
            @Override
            public void cancelClick(Component component) {

            }

            @Override
            public void confirmClick(Component component, String content) {
                revocable = abilitySlice.createSerialTaskDispatcher(dispatcherName, TaskPriority.DEFAULT).asyncDispatch(() -> {
                    IFileProcessor processor = cameraProcessor.getCameraProcessor(currentTypePage);
                    List<IBaseFileEntity> list = processor.getFileListByKeyword(content, currentTypePage);
                    updateFraction(list, currentTypePage);
                });
            }
        });
        inputDialog.show();
    }

    /**
     * 切换fraction
     */
    private void switchFraction(BaseFraction fraction) {
        if (abilitySlice != null && fractionManager != null) {
            abilitySlice.replaceFraction(ResourceTable.Id_fraction_container, fraction);
        }
    }

    private VideoHistoryListFraction getVideoHistoryListFraction() {
        if (videoHistoryListFraction == null) {
            videoHistoryListFraction = new VideoHistoryListFraction();
        }
        return videoHistoryListFraction;
    }

    private ImageHistoryListFraction getImageHistoryListFraction() {
        if (imageHistoryListFraction == null) {
            imageHistoryListFraction = new ImageHistoryListFraction();
        }
        return imageHistoryListFraction;
    }

    /**
     * 刷新当前查询界面
     *
     * @param list
     */
    private void updateFraction(List<IBaseFileEntity> list, FileType type) {
        switch (type) {
            case FILE_TYPE_VIDEO:
                videoHistoryListFraction.refreshVideoList(list);
                break;
            case FILE_TYPE_IMAGE:
                imageHistoryListFraction.refreshImageList(list);
                break;
        }
    }

    @Override
    public void onComponentBoundToWindow(Component component) {
        abilitySlice.getUITaskDispatcher().asyncDispatch(this::initFraction);
    }

    @Override
    public void onComponentUnboundFromWindow(Component component) {
        if (revocable != null) {
            revocable.revoke();
        }
    }

    @Override
    public Component getHistoryFraction() {
        return this;
    }

    @Override
    public void refreshFraction(FileType type) {
        revocable = abilitySlice.createSerialTaskDispatcher(dispatcherName, TaskPriority.DEFAULT).asyncDispatch(() -> {
            IFileProcessor processor = cameraProcessor.getCameraProcessor(type);
            List<IBaseFileEntity> list = processor.getFileList(currentTypePage);
            updateFraction(list, type);
        });
    }
}

